package action;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.bean.Language;
import model.bo.SearchWordBO;
import model.bo.WordManagerBO;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import form.WordManagerForm;

public class WordManagerAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		WordManagerForm wordManagerForm = (WordManagerForm) form;
		WordManagerBO wordManagerBO = new WordManagerBO();
		ArrayList<Language> listLanguage = new ArrayList<Language>();
		SearchWordBO searchWordBo = new SearchWordBO();
		listLanguage = searchWordBo.GetListLang();
		String langSource = wordManagerForm.getLangSource();
		String langTarget = wordManagerForm.getLangTarget();
		String word = wordManagerForm.getWord();
		String meaning = wordManagerForm.getMean();
		char breakPath = '\\';
		String img = wordManagerForm.getImg();
		if(img != null){
			int start = img.length()-1;
			int end = img.length();
			while (start > 0 && breakPath != img.charAt(start)){
				start--;
			}
			img = img.substring(start+1, end);
		}
		
		request.getAttribute("listLang");
		wordManagerForm.setListLanguage(listLanguage);
		if(word!=null ||!("".equals(word))){
		if ("Delete".equals(wordManagerForm.getBtnDelete())) {
			if(! wordManagerBO.CheckWord(langSource, langTarget, word))
			wordManagerBO.RemoveWord(langSource, langTarget, word);
		}

		if ("Add".equals(wordManagerForm.getBtnSubmit())) {
			if (!("".equals(word) || word != null)) {
			} else if (wordManagerBO.CheckWord(langSource, langTarget, word)) {
				wordManagerBO.EditWord(langSource, langTarget, word, meaning);
			} else {
				wordManagerBO.AddWord(langSource, langTarget, word, meaning,
						img);
			}
		}
		}
		request.setAttribute("listLang", listLanguage);
		return mapping.findForward("OK");
	}
}
